package Algorithm.search.swordOffer;

/**
 * 剑指 Offer 53 - I. 在排序数组中查找数字 I https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
 * 给定一个非递减数组，统计一个数字在数组中出现的次数
 */
public class CountTargetInOrderedNums {

    /**
     * 思路一：即第一个大于target的元素位置减去第一个大于target-1的元素位置，若target不存在则这两个位置相同，也成立
     */
    public int search(int[] nums, int target) {
        return find(nums, target) - find(nums, target-1);
    }

    public int find(int[] nums, int t) {
        int low = 0, high = nums.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (nums[mid] <= t) low = mid + 1;
            else high = mid - 1;
        }
        return low;
    }

    /**
     * 思路二：二分查找找到target后，再向左边和右边统计重复次数
     */
    public int search2(int[] nums, int target) {
        int low = 0, high = nums.length-1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (nums[mid] == target) {
                int count = 1, t = mid;
                while (--t >= 0 && nums[t] == target) count++;
                t = mid;
                while (++t < nums.length && nums[t] == target) count++;
                return count;
            } else if (nums[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return 0;
    }
}
